<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { entergamedata } from '@/api/chart'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.getChartData()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    getChartData() {
      const query = { 'pfid': [75, 77, 79, 137, 138, 153, 158, 202, 246, 272, 275], 'datetime': [new Date(Date.now() - 3600 * 1000 * 24 * 7), new Date()] }
      entergamedata(query).then(response => {
        this.handleData(response.data)
      })
    },
    handleData(data) {
      const datas = []
      const dates = new Map()
      data.forEach(item => {
        datas[item.channel_id] = []
        if (!dates.has(item.dates)) dates.set(item.dates, 1)
      })

      data.forEach(item => {
        datas[item.channel_id][item.dates] = parseInt(item.enter_count)
      })
      const days = []
      dates.forEach((v, date) => {
        days.push(date.substr(5))
      })

      datas.forEach((data, pfid) => {
        if (dates.size !== Object.keys(data).length) {
          const keys = Object.keys(data)
          dates.forEach((v, date) => {
            if (keys.indexOf(date) < 0) {
              datas[pfid][date] = 0
            }
          })
        }
      })
      const series = []
      datas.forEach((data, pfid) => {
        const keys = Object.keys(data)
        const values = []
        keys.sort().forEach(it => {
          values.push(data[it])
        })
        const chartjs = {
          'name': pfid,
          'type': 'bar',
          'stack': 'vistors',
          'barWidth': '60%',
          'data': values
        }
        series.push(chartjs)
      })
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOpt(series, days)
    },
    setOpt(series, date) {
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          top: 10,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          data: date,
          axisTick: {
            alignWithLabel: true
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          }
        }],
        series: series
      })
    }
  }
}
</script>
